package com.ayguigu.gulimall.ssoserver.controller;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class LoginController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/userInfo")
    @ResponseBody
    public String userInfo(@RequestParam(value = "token",required = false) String token){
            String loginUser = stringRedisTemplate.opsForValue().get(token);
            return loginUser;
    }


    @PostMapping("/doLogin")
    public String doLogin(String username,
                          String password,
                          String url,
                          HttpServletResponse response){
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //登录成功跳转，跳回到之前的页面
            //但在跳转之前，需要将用户的信息存到redis中
            //我们模拟单体系统下的session，在使用session的时候会自动生成一个SESSIONID，类似于银行卡号
            //为此我们把存进redis中的key便当做卡号，利用uuid来随机生成
            String uuid = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(uuid,username);
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);
            return "redirect:"+url+"?token="+uuid;
        }
        return "login";
    }

    /**
     * 还没登录的话，跳转登录服务器的登录页
     * @return
     */
    @RequestMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String redirect_url,
                            Model model,
                            @CookieValue(value = "sso_token",required = false) String sso_token){
        if(!StringUtils.isEmpty(sso_token)){
            //说明之前有人登陆过，给浏览器留下了痕迹
            return "redirect:"+redirect_url+"?token="+sso_token;
        }
        model.addAttribute("redirect_url",redirect_url);
        return "login";
    }
}
